package com.mh.study.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author MH
 * @since 2022-02-21
 */
@Slf4j
@RestController
@RequestMapping("auto-delivery")
public class AutoDeliveryController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/check-state/{userId}")
    public Integer checkState(@PathVariable String userId) {
        // 1545132
        List<ServiceInstance> instances = discoveryClient.getInstances("service-resume");
        ServiceInstance serviceInstance = instances.get(0);
        serviceInstance.getHost();
        String url = String.format("http://%s:%s/resume/open-state/%s",
                serviceInstance.getHost(), serviceInstance.getPort(), userId);
        return restTemplate.getForObject(url, Integer.class);
    }

    @GetMapping("/get-resume-port")
    public Integer getResumePort() {
        return restTemplate.getForObject("http://service-resume/resume/get-port", Integer.class);
    }

    @GetMapping("/get-resume-port-2")
    public Integer getResumePort2() {
        return restTemplate.getForObject("http://service-resume/resume/get-port-2", Integer.class);
    }
}
